<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
	<title>表单验证等问题</title>
	<link rel="stylesheet" href="../static/css/element2.css">
	<script src="../static/js/vue.global.prod.js"></script>
	<script src="../static/js/element-plue2.js"></script>
	
	<link rel="stylesheet" href="../static/css/com.css">
<style type="text/css">
.input-bl{
	display: inline-block;
	width: 406px;
}
.input-bl>.el-input__wrapper{
	width: 376px;
}
</style>
</head>
<body>
<div id="app" class="">
	<a href='Form1.html' class='layui-btn0'>典型表单，行内表单，对齐方式，表单校验</a>
	<a href='Form2.html' class='layui-btn'>自定义校验规则，添加/删除表单项，数字类型验证，尺寸控制，可访问性</a>
	
	<el-divider content-position="left">自定义校验规则</el-divider><!-- =============================================================== -->
	<p class="desc">这个例子中展示了如何使用自定义验证规则来完成密码的二次验证</p>
	<p class="desc">本例还使用status-icon属性为输入框添加了表示校验结果的反馈图标</p>
	<el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm w600">
		<el-form-item label="Pass" prop="pass">
			<el-input v-model="ruleForm.pass" type="password" autocomplete="off"></el-input>
		</el-form-item>
		<el-form-item label="CheckPass" prop="checkPass">
			<el-input v-model="ruleForm.checkPass" type="password" autocomplete="off"></el-input>
		</el-form-item>
		<el-form-item label="Age" prop="age">
			<el-input v-model.number="ruleForm.age"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
			<el-button @click="resetForm('ruleForm')">重置</el-button>
		</el-form-item>
	</el-form>
	
	<el-divider content-position="left">数字类型验证</el-divider><!-- =============================================================== -->
	<p class="desc">数字类型的验证需要在 v-model 处加上 number 的修饰符，这是 Vue 自身提供的用于将绑定值转化为 number 类型的修饰符。</p>
	<p class="desc">有时候把自定义效验规则写在el-from属性rules中会不生效，可以按下面的remark的方式写（直接在el-form-item的属性中写一个rules）。</p>
	<el-form ref="formRefNumber" :model="numberValidateForm" label-width="100px" class="w600">
		<el-form-item label="age" prop="age" :rules="[
			{ required: true,		message: 'age是必填的' },
			{ type: 'number',		message: 'age必须是一个数字' },
			{validator: this.validateAge,		trigger: 'blur'},
		]">
			<el-input v-model.number="numberValidateForm.age" type="text" autocomplete="off" />
		</el-form-item>
		<el-form-item label="remark" prop="remark" :rules="[{validator: this.validateHasCN, trigger: 'blur'}]" :required="true">
			<!-- <el-input v-model="numberValidateForm.remark" type="text" autocomplete="off" /> -->
			<el-input v-model="numberValidateForm.remark" class="input-width" rows=3 maxlength="800" show-word-limit type="textarea" placeholder="如果要填写备注，必须有中文汉字..."></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm('formRefNumber')">Submit</el-button>
			<el-button @click="resetForm('formRefNumber')">Reset</el-button>
		</el-form-item>
	</el-form>
	
	<el-divider content-position="left">一些用法介绍</el-divider><!-- =============================================================== -->
	<p class="desc">Form 事件：validate	任一表单项被校验后触发。</p>
	<el-form ref="otherRef" :model="otherData" label-width="100px" class="w600" @validate="theValidate">
		<!-- <template #default>
			<span>这是Form Slots</span>
		</template> -->
		<el-form-item label="姓名" prop="name" :required="true">
			<el-input v-model="otherData.name" type="text" autocomplete="off" />
		</el-form-item>
		
		<el-form-item label="介绍" prop="remark" :rules="[{validator: this.validateHasCN, trigger: 'blur'}]" :required="true">
			<el-input v-model="otherData.remark" class="input-width" rows=3 maxlength="800" show-word-limit type="textarea" placeholder="如果要填写备注，必须有中文汉字..."></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm('otherRef')">Submit</el-button>
			<el-button @click="resetForm('otherRef')">Reset</el-button>
		</el-form-item>
	</el-form>
	<p class="desc">点击一下按钮，触发一些事件：</p>
	<div style="margin-left: 30px;">
		<el-button @click="tgValidate('otherRef')">Validate</el-button> <span>对整个表单的内容进行验证。 接收一个回调函数，或返回 Promise。</span> <br>
		<el-button @click="tgValidateField('otherRef')">ValidateField</el-button> <span>验证具体的某个字段。</span> <br>
		
		<el-button @click="tgScrollToField('otherRef')">ScrollToField</el-button> <span>滚动到指定的字段。</span> <br>
		<el-button @click="tgClearValidate('otherRef')">ClearValidate</el-button> <span>清理某个字段的表单验证信息。</span> <br>
	</div>
	
	<el-divider content-position="left">FormItem Slots 表单项的插槽</el-divider><!-- =============================================================== -->
	<p class="desc">利用FormItem Slots改变FormItem的显示。</p>
	<el-form ref="formItemRef" :model="formItemData" label-width="100px" class="w600" @validate="theValidate">
		<el-form-item ref="nameRef" label="姓名" prop="name" label-width="100px" :required="true" size="small">
			<template #label>
				姓<span style="color: red;">名</span>
			</template>
			<el-input v-model="formItemData.name" type="text" autocomplete="off" />
		</el-form-item>
		
		<el-form-item ref="remarkRef" label="介绍" prop="remark" :rules="[{validator: this.validateHasCN, trigger: 'blur'}]" :required="true">
			<el-input v-model="formItemData.remark" class="input-width" rows=3 maxlength="800" show-word-limit type="textarea" placeholder="如果要填写备注，必须有中文汉字..."></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitForm('formItemRef')">Submit</el-button>
			<el-button @click="resetForm('formItemRef')">Reset</el-button>
		</el-form-item>
	</el-form>
	<p class="desc">点击一下按钮，触发一些事件：</p>
	<div style="margin-left: 30px;">
		<el-button @click="fiSize('nameRef')">Size</el-button> <span>表单项大小。</span> <br>
		<el-button @click="fiValidateMessage('remarkRef')">ValidateMessage</el-button> <span>校验消息。</span> <br>
		<el-button @click="fiResetField('remarkRef')">Validate</el-button> <span>对该表单项进行重置，将其值重置为初始值并移除校验结果。</span> <br>
	</div>
	
	<div style="height: 1000px;"></div>
</div>
</body>
<script>
const ValidateObj = {
	//判断数据是否包含中文（包含中文返回true）
	has_cn: function(str){
		if(str == ''){
			return false;
		}else{
			if(/.*[\u4e00-\u9fa5]+.*$/.test(str)){
				return true;
			}else{
				return false;
			}
		}
	},
}

const Main = {
	data() {
		return {
			numberValidateForm: {
				age: '',
				remark: '',
			},
			ruleForm: {
				pass: '',
				checkPass: '',
				age: '',
			},
			rules: {
				pass: [
					{validator: this.validatePass,			trigger: 'blur'},
				],
				checkPass: [
					{validator: this.validateCheckPass,		trigger: 'blur'},
				],
				age: [
					{validator: this.validateAge,			trigger: 'blur'},
				],
			},
			
			otherData: {
				name: '',
				remark: '',
			},
			formItemData: {
				name: '',
				remark: '',
			},
			
		}
	},
	methods:{
		// Form 事件
		tgValidate(formName){
			let re = this.$refs[formName].validate();
			console.log('返回的Promise：', re);
			// console.log(re['[[Prototype]]']);
		},
		tgValidateField(formName){
			let re = this.$refs[formName].validateField(['name', 'remark']);
			console.log('返回指定字段的验证结果：', re);
		},
		tgScrollToField(formName){
			this.$refs[formName].scrollToField(['remark']);
			console.log('滚动到指定的字段');
		},
		tgClearValidate(formName){
			this.$refs[formName].clearValidate(['remark']);
			console.log('清理某个字段的表单验证信息');
		},
		
		// FormItem事件
		fiSize(refName){
			let re = this.$refs[refName].size;
			console.log('姓名的表单项大小', re);
		},
		fiValidateMessage(refName){
			let re = this.$refs[refName].validateMessage;
			console.log('校验消息', re);
		},
		fiResetField(refName){
			this.$refs[refName].resetField();
			console.log('对该表单项进行重置，将其值重置为初始值并移除校验结果');
		},
		
		theValidate(prop, isValid, message){
			console.log(prop);
			console.log(isValid);
			console.log(message);
		},
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					console.log('submit success!');
					if(formName == "ruleForm"){
						console.log(this.ruleForm);
					}else if(formName == "formRef"){
						console.log(this.dynamicValidateForm);
					}else if(formName == "formRefNumber"){
						console.log(this.numberValidateForm);
					}else if(formName == "formSize"){
						console.log(this.sizeForm);
					}else if(formName == "formFull"){
						console.log(this.formAccessibility);
					}
				} else {
					console.log('error submit!!')
					return false
				}
			})
		},
		resetForm(formName) {
			console.log("resetForm");
			this.$refs[formName].resetFields();
		},
		
		validatePass(rule, value, callback){
			if (value === '') {
				callback(new Error('请输入密码！'))
			} else {
				if (this.ruleForm.checkPass !== '') {
					this.$refs.ruleForm.validateField('checkPass')
				}
				callback()
			}
		},
		validateCheckPass(rule, value, callback){
			if (value === '') {
				callback(new Error('请重新输入密码！'))
			} else if (value !== this.ruleForm.pass) {
				callback(new Error("两次输入不匹配！"))
			} else {
				callback()
			}
		},
		validateAge(rule, value, callback){
			if (!value) {
				return callback(new Error('请输入年龄'))
			}
			setTimeout(() => {
				if (!Number.isInteger(value)) {
					callback(new Error('请输入数字'))
				} else {
					if (value < 18) {
						callback(new Error('年龄必须大于等于18岁'))
					} else if(value >= 126){
						callback(new Error('超过126岁的就不要来了'))
					}else{
						callback()
					}
				}
			}, 300)
		},
		//验证备注（为空，或必须包含中文）
		validateHasCN(rule, value, callback){
			if(value == ''){
				callback(new Error('点了，就得写点东西。'));
			}else{
				if(ValidateObj.has_cn(value)){
					callback();
				}else{
					return callback(new Error('备注中必须包含中文汉字。'));
				}
			}
		},
		
	}
}
const app = Vue.createApp(Main);
app.use(ElementPlus);
app.mount("#app");

</script>
</html>
